import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../constants/constants.dart';
import 'player_screen.dart';

/// 收藏页面
/// 显示用户收藏的音乐列表
class FavoritesScreen extends StatefulWidget {
  const FavoritesScreen({super.key});

  @override
  State<FavoritesScreen> createState() => _FavoritesScreenState();
}

class _FavoritesScreenState extends State<FavoritesScreen>
    with TickerProviderStateMixin {
  late AnimationController _fadeController;
  late Animation<double> _fadeAnimation;

  List<Music> _favoritesList = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initAnimations();
    _loadFavorites();
  }

  /// 初始化动画
  void _initAnimations() {
    _fadeController = AnimationController(
      duration: AppTheme.animationDurationMedium,
      vsync: this,
    );
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeInOut,
    ));
  }

  /// 加载收藏列表
  Future<void> _loadFavorites() async {
    try {
      final musicLibraryService =
          Provider.of<MusicLibraryService>(context, listen: false);
      final favorites = musicLibraryService.getFavoriteMusic();

      setState(() {
        _favoritesList = favorites;
        _isLoading = false;
      });

      _fadeController.forward();
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _showErrorSnackBar('加载收藏列表失败: $e');
    }
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppTheme.errorColor,
      ),
    );
  }

  @override
  void dispose() {
    _fadeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: AppTheme.backgroundGradientDark,
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部标题栏
              _buildHeader(),

              // 收藏列表
              Expanded(
                child: _isLoading
                    ? _buildLoadingState()
                    : _favoritesList.isEmpty
                        ? _buildEmptyState()
                        : _buildFavoritesList(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(AppTheme.spacingMedium),
      child: Row(
        children: [
          // IconButton(
          //   onPressed: () => Navigator.of(context).pop(),
          //   icon: const Icon(
          //     Icons.arrow_back,
          //     color: AppTheme.textPrimaryDark,
          //     size: AppTheme.iconSizeLarge,
          //   ),
          // ),
          const Expanded(
            child: Text(
              '我的收藏',
              style: TextStyle(
                fontSize: AppTheme.fontSizeXL,
                fontWeight: FontWeight.bold,
                color: AppTheme.textPrimaryDark,
              ),
            ),
          ),
          if (_favoritesList.isNotEmpty)
            IconButton(
              onPressed: _playAllFavorites,
              icon: const Icon(
                Icons.play_arrow,
                color: AppTheme.primaryColor,
                size: AppTheme.iconSizeLarge,
              ),
            ),
        ],
      ),
    );
  }

  /// 构建加载状态
  Widget _buildLoadingState() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
          ),
          SizedBox(height: AppTheme.spacingMedium),
          Text(
            '正在加载收藏列表...',
            style: TextStyle(
              fontSize: AppTheme.fontSizeMedium,
              color: AppTheme.textSecondaryDark,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: AppTheme.albumCoverSizeLarge,
            height: AppTheme.albumCoverSizeLarge,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: AppTheme.surfaceDark,
              border: Border.all(
                color: AppTheme.primaryColor.withOpacity(0.3),
                width: 2,
              ),
            ),
            child: const Icon(
              Icons.favorite_border,
              size: AppTheme.iconSizeXL,
              color: AppTheme.textHintDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingLarge),
          const Text(
            '暂无收藏音乐',
            style: TextStyle(
              fontSize: AppTheme.fontSizeLarge,
              color: AppTheme.textSecondaryDark,
            ),
          ),
          const SizedBox(height: AppTheme.spacingMedium),
          const Text(
            '在音乐列表中点击收藏按钮\n来添加你喜欢的音乐',
            style: TextStyle(
              fontSize: AppTheme.fontSizeMedium,
              color: AppTheme.textHintDark,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: AppTheme.spacingXL),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: const Text('浏览音乐库'),
          ),
        ],
      ),
    );
  }

  /// 构建收藏列表
  Widget _buildFavoritesList() {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: Column(
        children: [
          // 统计信息
          Container(
            margin: const EdgeInsets.symmetric(
              horizontal: AppTheme.spacingMedium,
            ),
            padding: const EdgeInsets.all(AppTheme.spacingMedium),
            decoration: BoxDecoration(
              color: AppTheme.surfaceDark,
              borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
              border: Border.all(
                color: AppTheme.primaryColor.withOpacity(0.3),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                const Icon(
                  Icons.favorite,
                  color: AppTheme.errorColor,
                  size: AppTheme.iconSizeMedium,
                ),
                const SizedBox(width: AppTheme.spacingSmall),
                Text(
                  '共 ${_favoritesList.length} 首收藏音乐',
                  style: const TextStyle(
                    fontSize: AppTheme.fontSizeMedium,
                    color: AppTheme.textPrimaryDark,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const Spacer(),
                Text(
                  _getTotalDuration(),
                  style: const TextStyle(
                    fontSize: AppTheme.fontSizeSmall,
                    color: AppTheme.textSecondaryDark,
                  ),
                ),
              ],
            ),
          ),

          const SizedBox(height: AppTheme.spacingMedium),

          // 音乐列表
          Expanded(
            child: ListView.builder(
              padding: const EdgeInsets.symmetric(
                horizontal: AppTheme.spacingMedium,
              ),
              itemCount: _favoritesList.length,
              itemBuilder: (context, index) {
                final music = _favoritesList[index];
                return _buildMusicItem(music, index);
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建音乐项
  Widget _buildMusicItem(Music music, int index) {
    return Consumer<AudioPlayerService>(
      builder: (context, audioService, child) {
        final isCurrentMusic = audioService.currentMusic?.id == music.id;
        final isPlaying = isCurrentMusic && audioService.isPlaying;

        return Container(
          margin: const EdgeInsets.only(bottom: AppTheme.spacingSmall),
          decoration: BoxDecoration(
            color: isCurrentMusic
                ? AppTheme.primaryColor.withOpacity(0.1)
                : AppTheme.surfaceDark,
            borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
            border: isCurrentMusic
                ? Border.all(
                    color: AppTheme.primaryColor.withOpacity(0.5),
                    width: 1,
                  )
                : null,
          ),
          child: ListTile(
            contentPadding: const EdgeInsets.symmetric(
              horizontal: AppTheme.spacingMedium,
              vertical: AppTheme.spacingSmall,
            ),
            leading: _buildMusicCover(music, isPlaying),
            title: Text(
              music.title,
              style: TextStyle(
                fontSize: AppTheme.fontSizeMedium,
                fontWeight:
                    isCurrentMusic ? FontWeight.w600 : FontWeight.normal,
                color: isCurrentMusic
                    ? AppTheme.primaryColor
                    : AppTheme.textPrimaryDark,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  music.artist,
                  style: const TextStyle(
                    fontSize: AppTheme.fontSizeSmall,
                    color: AppTheme.textSecondaryDark,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                if (music.album != null) ...[
                  const SizedBox(height: 2),
                  Text(
                    music.album!,
                    style: const TextStyle(
                      fontSize: AppTheme.fontSizeXS,
                      color: AppTheme.textHintDark,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ],
            ),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  music.formattedDuration,
                  style: const TextStyle(
                    fontSize: AppTheme.fontSizeSmall,
                    color: AppTheme.textSecondaryDark,
                  ),
                ),
                const SizedBox(width: AppTheme.spacingSmall),
                IconButton(
                  onPressed: () => _removeFavorite(music),
                  icon: const Icon(
                    Icons.favorite,
                    color: AppTheme.errorColor,
                    size: AppTheme.iconSizeMedium,
                  ),
                ),
              ],
            ),
            onTap: () => _playMusic(music, index),
          ),
        );
      },
    );
  }

  /// 构建音乐封面
  Widget _buildMusicCover(Music music, bool isPlaying) {
    return Container(
      width: AppTheme.albumCoverSizeMedium,
      height: AppTheme.albumCoverSizeMedium,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
        gradient: AppTheme.primaryGradient,
      ),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
            child: music.coverArt != null
                ? Image.asset(
                    music.coverArt!,
                    width: AppTheme.albumCoverSizeMedium,
                    height: AppTheme.albumCoverSizeMedium,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return _buildDefaultMusicCover();
                    },
                  )
                : _buildDefaultMusicCover(),
          ),
          if (isPlaying)
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
                color: Colors.black.withOpacity(0.5),
              ),
              child: const Center(
                child: Icon(
                  Icons.equalizer,
                  color: AppTheme.primaryColor,
                  size: AppTheme.iconSizeMedium,
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建默认音乐封面
  Widget _buildDefaultMusicCover() {
    return Container(
      width: AppTheme.albumCoverSizeMedium,
      height: AppTheme.albumCoverSizeMedium,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
        gradient: AppTheme.primaryGradient,
      ),
      child: const Icon(
        Icons.music_note,
        color: Colors.white,
        size: AppTheme.iconSizeMedium,
      ),
    );
  }

  /// 获取总时长
  String _getTotalDuration() {
    final totalSeconds = _favoritesList.fold<int>(
      0,
      (sum, music) => sum + music.duration,
    );

    final hours = totalSeconds ~/ 3600;
    final minutes = (totalSeconds % 3600) ~/ 60;

    if (hours > 0) {
      return '$hours小时$minutes分钟';
    } else {
      return '$minutes分钟';
    }
  }

  /// 播放音乐
  void _playMusic(Music music, int index) {
    final audioService =
        Provider.of<AudioPlayerService>(context, listen: false);

    // 设置播放列表并播放指定音乐
    audioService.playMusic(music, playlist: _favoritesList, index: index);

    // 导航到播放页面
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const PlayerScreen(),
      ),
    );
  }

  /// 播放所有收藏
  void _playAllFavorites() {
    if (_favoritesList.isEmpty) return;

    final audioService =
        Provider.of<AudioPlayerService>(context, listen: false);

    // 设置播放列表并播放第一首
    audioService.playMusic(_favoritesList.first, playlist: _favoritesList, index: 0);

    // 导航到播放页面
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const PlayerScreen(),
      ),
    );
  }

  /// 移除收藏
  void _removeFavorite(Music music) async {
    try {
      final musicLibraryService =
          Provider.of<MusicLibraryService>(context, listen: false);
      await musicLibraryService.toggleFavorite(music);

      // 从列表中移除
      setState(() {
        _favoritesList.removeWhere((m) => m.id == music.id);
      });

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('已取消收藏'),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        _showErrorSnackBar('操作失败: $e');
      }
    }
  }
}
